import traceback

manual_result = [
    {'res': '36_1-205-5', 'userId': 401},
    {'res': '34_2-207-5', 'userId': 404},
    {'res': '34_2-206-5', 'userId': 404},
    {'res': '18_2-', 'userId': 404}
]
error_points = []
for item in manual_result:  # manual_result is [{  "userId":230, "res":"3_1-205-5" }, {  "userId":230, "res":"3_1-205-5" }](list)
    inspect_res = item["res"] if "res" in item else item
    user_id = item["userId"] if "userId" in item else ""
    if "-" in str(inspect_res):
        tmp = str(inspect_res).split("-")
        errorPositionId = tmp[1]
        if len(tmp) > 2:
            defectiveIds = [int(tmp[2])]
        else:
            defectiveIds = [9]
        if errorPositionId != "" and str(errorPositionId) != "0":
            # 上报质检结果，最好再进行适配
            error_point = dict(userId=user_id, errorPositionId=errorPositionId, defectiveIds=defectiveIds)  # 不合格
            error_points.append(error_point)


def format_error_points_for_submit_for_v3(error_points):
    # [{'userId': 401, 'errorPositionId': '205', 'defectiveIds': [5]}, {'userId': 404, 'errorPositionId': '207', 'defectiveIds': [5]}, {'userId': 404, 'errorPositionId': '206', 'defectiveIds': [5]}]
    # dict(userId=user_id, errorPositionId=errorPositionId, defectiveIds=defectiveIds)  # 不合格
    try:
        grouped_by_error_pos = {}
        for item in error_points:
            error_pos_id = item["errorPositionId"]
            # 若键不存在，先初始化一个空列表
            if error_pos_id not in grouped_by_error_pos:
                grouped_by_error_pos[error_pos_id] = []
            grouped_by_error_pos[error_pos_id].append(item)

        print(f"-------grouped_by_error_pos: {grouped_by_error_pos}")


        item_flaws = list()
        for errorPositionId in grouped_by_error_pos.keys():
            print(f"-------errorPositionId: {errorPositionId}")
            ll = grouped_by_error_pos[errorPositionId]
            userId = ""
            defectiveIds = list()
            for item in ll:
                if "userId" in item:
                    userId = item["userId"]
                defectiveIds.extend(item["defectiveIds"])
            item_flaws.append(dict(userId=userId, errorPosition=errorPositionId, defectiveIds=defectiveIds))
        return item_flaws
    except:
        err = traceback.format_exc()
        print(f"------error:{err}")


print(f"-----error_points:{error_points}")
flaws = format_error_points_for_submit_for_v3(error_points)
print(f"-----flaws:{flaws}")


